import { defineStore } from "pinia";
import { store } from "@/store";
import { ref } from "vue";
import { HMI_SETTING_ZONE_API } from "@/api/hmi/setting-zone.api";
import type { SettingZoneInfo } from "@/api/hmi/setting-zone.api";

/**
 * 定值区 Store
 */
export const useSettingZoneStore = defineStore("settingZone", () => {
  // 响应式状态
  const activeZone = ref<number>(0);
  const displayZone = ref<number>(0);
  const minZone = ref<number>(0);
  const maxZone = ref<number>(0);
  const zoneList = ref<number[]>([]);
  const isReady = ref<boolean>(false);

  // 设置函数
  const setDisplayZone = (zone: number) => {
    displayZone.value = zone;
  };

  const setZoneInfo = (active_zone: number, min_zone: number, max_zone: number) => {
    activeZone.value = active_zone;
    if (displayZone.value < min_zone || displayZone.value > max_zone) {
      displayZone.value = active_zone;
    }
    minZone.value = min_zone;
    maxZone.value = max_zone;
    isReady.value = true;
  };

  const setZoneList = (list: any[]) => {
    zoneList.value = list.map(Number);
  };

  // API 调用函数
  const setActiveZone = (apiPath: string, zone: number) => {
    return new Promise((resolve, reject) => {
      HMI_SETTING_ZONE_API.setActiveZone(apiPath, zone)
        .then((res) => {
          setZoneInfo(res.active_zone, res.min_zone, res.max_zone);
          resolve(res);
        })
        .catch((error) => {
          console.error("setActiveZone error:", error);
          reject(error);
        });
    });
  };

  const activateDisplayZone = (apiPath: string) => {
    return setActiveZone(apiPath, displayZone.value);
  };

  const fetchSettingZoneInfo = (apiPath: string) => {
    return new Promise<SettingZoneInfo>((resolve, reject) => {
      HMI_SETTING_ZONE_API.fetchSettingZoneInfo(apiPath)
        .then((res) => {
          zoneList.value = [
            ...Array.from({ length: res.max_zone - res.min_zone + 1 }, (_, i) => res.min_zone + i),
          ];
          setZoneInfo(res.active_zone, res.min_zone, res.max_zone);
          resolve(res);
        })
        .catch((error) => {
          console.error("fetchSettingZoneInfo error:", error);
          reject(error);
        });
    });
  };

  // 定值区拷贝
  const copyZone = (cpu: number, srcZone: number, dstZone: number) => {
    return new Promise((resolve, reject) => {
      HMI_SETTING_ZONE_API.copyZone(cpu, srcZone, dstZone)
        .then((res) => {
          resolve(res);
        })
        .catch((error) => {
          reject(error);
        });
    });
  };

  return {
    isReady,
    activeZone,
    displayZone,
    minZone,
    maxZone,
    zoneList,
    setActiveZone,
    setDisplayZone,
    activateDisplayZone,
    setZoneInfo,
    setZoneList,
    fetchSettingZoneInfo,
    copyZone,
  };
});

/**
 * 适用于 setup 之外的场景
 */
export function useSettingZoneStoreHook() {
  return useSettingZoneStore(store);
}
